package com.gogowan.agroenterprise;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.RetrofitUtil.GsonUtil;

import android.app.AlertDialog;
import android.app.Instrumentation;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * 
 * 自动更新页面，用到了 res/value/envs.xml/ 中的 url 网址，访问服务器自动下载
 * 
 * @author zk
 * 
 */
public class UpdateActivity extends BaseActivity {
	/**
	 * 地址
	 */
	private String updateUrl = "";
	/**
	 * 进度框
	 */
	private ProgressBar bar = null;
	/**
	 * 文本框
	 */
	private TextView jindu = null, ratio = null;
	/**
	 * 文件大小
	 */
	private int size, toSize;
	private UpdateAsync updateAsync;
	public void onCreate(Bundle savedInstanceState) {
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sp_update);

		bar = (ProgressBar) findViewById(R.id.myView_ProgressBar);
		jindu = (TextView) findViewById(R.id.jindu);
		ratio = (TextView) findViewById(R.id.ratio);
		
		try {
			Bundle bundle = getIntent().getExtras();
			String[] data = bundle.getStringArray("token");
			Log.e("1994122", GsonUtil.GsonString(data));
			bundle.clear();
			updateUrl = data[0].toString();
		    updateAsync = new UpdateAsync();
		    updateAsync.execute();
			
		} catch (NullPointerException npe) {
			Log.e("1994122", GsonUtil.GsonString(npe));
			exitfinish();
		} catch (Exception e) {
			Log.e("1994122", GsonUtil.GsonString(e));
			exitfinish();
		}

	}
	/**
	 * 更新失败退出
	 */
	public void exitfinish()
	{
		AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("更新失败，请重新启动");
        builder.setCancelable(false);
        builder.setNegativeButton("确定", new OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                UpdateActivity.this.finish();
            }
        });

        builder.create().show();
	}
	/**
	 * 更新下载处理
	 * 
	 * @author zk
	 * 
	 */
	private class UpdateAsync extends AsyncTask<Integer, Integer, String> {
		@Override
		protected String doInBackground(Integer... params) {

			File file = null;
			FileOutputStream fileOutput = null;
			InputStream inputStream = null;
			String filePath = null;
			try {
				URL urls = new URL(updateUrl);
				HttpURLConnection urlConnection = (HttpURLConnection) urls
						.openConnection();

				urlConnection.setRequestMethod("GET");
				//urlConnection.setDoOutput(true);
				urlConnection.connect();
				// CodeUpdate update=new CodeUpdate();
				// update.upgrade();

				File SDCardRoot = Environment.getExternalStorageDirectory();

				file = new File(SDCardRoot, "NCPSystem.apk");

				fileOutput = new FileOutputStream(file);

				inputStream = urlConnection.getInputStream();

				int totalSize = urlConnection.getContentLength();

				int downloadedSize = 0;

				byte[] buffer = new byte[1024];
				int bufferLength = 0;

				while ((bufferLength = inputStream.read(buffer)) > 0) {
					try {

						Thread.sleep(5);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						// e.printStackTrace();
					}
					fileOutput.write(buffer, 0, bufferLength);

					downloadedSize += bufferLength;
					Log.d("progress is ",
							String.valueOf((int) (((double) downloadedSize / (double) totalSize) * 100)));
					publishProgress(new Integer[] { (int) (((double) downloadedSize / (double) totalSize) * 100) });
					size = downloadedSize / 1024;
					toSize = totalSize / 1024;
				}
				urlConnection.disconnect();
				filePath = file.getPath();
			} catch (MalformedURLException ee) {
				Log.e("1994122","MalformedURLException ee :"+GsonUtil.GsonString(ee)+"\n");
				// ee.printStackTrace();
				filePath = null;
			} catch (IOException ea) {
				 ea.printStackTrace();
				Log.e("1994122","IOException ea :"+GsonUtil.GsonString(ea)+"\n");
				filePath = null;
			} finally {
				try {
					if (fileOutput != null)
						fileOutput.close();
					if (inputStream != null)
						inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
					Log.e("1994122","IOException e:  "+GsonUtil.GsonString(e)+"\n");
					filePath = null;
				}
			}
			return filePath;
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			bar.setProgress(progress[0]);
			jindu.setText("下载进度: \t" + size + "kb/" + toSize + "kb");
			ratio.setText(progress[0] + "%");
		}

		@Override
		protected void onPostExecute(String result) {
			// 运行安装
//			ActivityTest at = new ActivityTest();
//			try {
//				at.testStartActivity();
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			if(result==null||result.equals(""))
			{
				Log.e("1994122","接收失败");
				exitfinish();
				return;
			}
			bar.setProgress(0);
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(new File(result)),
					"application/vnd.android.package-archive");
			// startActivity(intent);
			startActivityForResult(intent, 0);
			android.os.Process.killProcess(android.os.Process.myPid());
			// Closeme();
		}
	}

	/**
	 * 安装软件
	 * 
	 * @author zk
	 * 
	 */
//	public class ActivityTest extends InstrumentationTestCase {
//
//		private Instrumentation mInst = null;
//		private ContentResolver mContentResolver = null;
//
//		@Override
//		protected void setUp() throws Exception {
//			super.setUp();
//			mInst = getInstrumentation();
//			mContentResolver = mInst.getContext().getContentResolver();
//			Log.d("mInst", mInst.toString());
//			Log.d("mContentResolver", mContentResolver.toString());
//		}
//
//		public void testStartActivity() throws Exception {
//			// launch activity
//			Intent intent = new Intent(Intent.ACTION_MAIN);
//			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			// String activityPackagePath = "com.android.";
//			// intent.setClassName(activityPackagePath,
//			// this.getClass().getName());
//			// TargetActivity mActivity = (TargetActivity)
//			// getInstrumentation().startActivitySync(intent);
//			// mInst.waitForIdleSync();
//			// send keyevent to press button
//			mInst.sendCharacterSync(KeyEvent.KEYCODE_DPAD_DOWN);
//			mInst.sendCharacterSync(KeyEvent.KEYCODE_DPAD_CENTER);
//			mInst.waitForIdleSync();
//		}
//
//	}

	// private void Closeme()
	// {
	// Uri packageURI = Uri.parse("package:com.BicycleManagementSystem");
	// Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
	// startActivity(uninstallIntent);
	// //Runtime.getRuntime().exec(prog)
	// }

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Log.d("keyCode=", ""+keyCode);
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			AlertDialog.Builder builder=new AlertDialog.Builder(this);
	        builder.setTitle("提示");
	        builder.setMessage("是否取消下载");
	        builder.setPositiveButton("确定", new OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	if(!updateAsync.isCancelled())
	            	{
	            		updateAsync.cancel(true);
	            	}
	            	UpdateActivity.this.finish();
	            }
	        });
	        builder.setNegativeButton("取消", new OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	                //
	            }
	        });
	        builder.create().show();
			return true;
			// case KeyEvent.FLAG_CANCELED:return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}